package com.jumper.property.comparer.core.convert.impl;

import com.alibaba.fastjson.JSON;
import com.jumper.property.comparer.core.convert.PropertyConverter;
import com.jumper.property.comparer.core.annotations.convert.LocalDateFormat;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;
import java.time.*;
import java.time.format.DateTimeFormatter;

/**
 * 本地时间属性转换器
 */
@Slf4j
public class LocalDatePropertyConverter implements PropertyConverter {

    @Override
    public Object convert(Object propertyValue, Field field) {
        if (propertyValue == null) {
            return null;
        }
        LocalDateFormat dateFormat = field.getAnnotation(LocalDateFormat.class);
        if (dateFormat == null) {
            return propertyValue;
        }
        try {
            ZonedDateTime zoneDateTime = LocalDateTime.of(((LocalDate) propertyValue), LocalTime.MIN).atZone(ZoneOffset.systemDefault());
            zoneDateTime = zoneDateTime.withZoneSameInstant(ZoneOffset.of(dateFormat.zoneOffset()));
            return zoneDateTime.toLocalDateTime().format(DateTimeFormatter.ofPattern(dateFormat.pattern()));
        } catch (Exception e) {
            log.warn("LocalDate格式转换异常:{}", JSON.toJSONString(propertyValue), e);
        }
        return propertyValue;
    }
}
